package sensornetwork.sensor;

import snifc.sensor.MemoryIfc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.Iterator;
import java.util.TreeSet;
import snifc.PacketIfc;
import sensornetwork.Packet;
import java.lang.InterruptedException;


public class Memory implements MemoryIfc{
	private int idSensor;
	private ArrayBlockingQueue memory;
	private int taille;
	
	public Memory (int idSensor, int taille){
		this.idSensor = idSensor;
		this.memory = new ArrayBlockingQueue(taille);
		this.taille = taille;
	}
	
	public String toString(){
		TreeSet ss=new TreeSet(this.memory); 
		StringBuffer sb=new StringBuffer("Sensor # ");
		sb.append(this.idSensor);
		sb.append(" has stored : ");
    int boucle = 0;
    for(Iterator it = ss.iterator(); it.hasNext(); sb.append("-")) {
      sb.append(((Packet)it.next()).getId());
      boucle++;
    }
    if (boucle == 0) {
      sb.append("is empty");
    }
		return sb.toString();
	}
	

	public boolean store(PacketIfc p){
		boolean isStored = true; 
    try {
      if (memory.contains(p)){
        isStored = false;
        System.out.println("Packet n " + p.getId() + " droped on sensor # " + idSensor);
      } else {
        isStored = true;
        if(memory.size() == taille){
          memory.poll();
        }
        memory.put(p);
        System.out.println("Paquet n "+p.getId()+" stored on sensor # "+idSensor);
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    } 
		return isStored;
	}
}
